package cn.tedu.fy.pethome.config;

import cn.tedu.fy.pethome.filter.JwtAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthorizationFilter jwtAuthorizationFilter;

    private String[] urls ={ "/admins/login",
            "/index.html",
            "/**/*.css",
            "/**/*.js",
            "/**/*.png",
            "/**/*.jpg",
            "/**/*.jpeg",
            "/",
            "/favicon.ico",
            "/swagger-resources",
            "/v2/api-docs",
            "/doc.html","/adminLogin.html"};
    @Bean
    public BCryptPasswordEncoder getEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    public SecurityConfiguration() {
      log.debug("Security安保系统已经启动了");
    }
    //  配置白名单
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();  //禁用防止跨域访问

        http.authorizeRequests()//所有请求必须授权才能被访问
                .antMatchers(HttpMethod.OPTIONS,"/**")//复杂类请求允许直接访问
                .permitAll()
                .antMatchers(urls)
                .permitAll()
                .anyRequest()
                .authenticated();//其他请求必须被认证过后后才能被访问

        // 缺失以下
        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
